package com.sinosoft.vaccinetoai.server.business.base.server;


import com.sinosoft.vaccinetoai.exception.BusinessException;
import com.sinosoft.vaccinetoai.exception.ExceptionEnums;
import com.sinosoft.vaccinetoai.security.model.CustomPrincipal;
import com.sinosoft.vaccinetoai.security.shiro.SSOAuthenticationToken;
import com.sinosoft.vaccinetoai.security.utils.SecurityUtils;
import com.sinosoft.vaccinetoai.server.business.base.server.model.LoginResModel;
import lombok.extern.slf4j.Slf4j;


import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 登录服务
 * @author xzh
 * @date 2023-07-10 17:47
 * @since 1.0.0
 */
@Component
@Slf4j
public class LoginServer {



    @Transactional(rollbackFor = Exception.class)
    public LoginResModel login(SSOAuthenticationToken authenticationToken) throws Exception {
        /**
         * 验证
         */
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(authenticationToken);
        }catch (Exception e) {
            if(e instanceof UnknownAccountException) {
                throw BusinessException.ofExceptionEnums(ExceptionEnums.LOGIN_AUTHC_FAIL);
            }else if(e instanceof IncorrectCredentialsException) {
                throw BusinessException.ofExceptionEnums(ExceptionEnums.LOGIN_PASSWORD_INVALID);
            }else if(e instanceof LockedAccountException) {
                throw BusinessException.ofExceptionEnums(ExceptionEnums.LOGIN_USER_STATUS_INVALID);
            }else {
                throw BusinessException.ofExceptionEnums(ExceptionEnums.LOGIN_AUTHC_FAIL);
            }
        }
        CustomPrincipal principal = SecurityUtils.getPrincipal();

        /**
         * 返回
         */
        LoginResModel loginModel = new LoginResModel();
        loginModel.setToken(subject.getSession().getId() + "");
        loginModel.setExpire(subject.getSession().getTimeout());
        loginModel.setUserId(principal.getUserId());
        loginModel.setName(principal.getLoginName());
        loginModel.setType(principal.getType());
        loginModel.setOrgSSO(principal.getOrgSSO());
        return loginModel;
    }


}
